#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'使用@property ，方便获取和设置元素值'


class Student_old(object):
    def __init__(self, score):
        self.__score = score

    def get_score(self):
        return self.__score

    def set_score(self, value):
        self.__score = value


so = Student_old(70)
so.set_score(80)  # 80
print(so.get_score())


class Student_new(object):
    def __init__(self, score):
        self.__score = score

    @property
    def score(self):
        return self.__score

    @score.setter
    def score(self, value):
        self.__score = value


sn = Student_new(70)
sn.score = 80
print(sn.score)  # 80


class Fruit(object):

    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    # 定义name属性是可读写的
    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        self.__name = value

    # 定义age属性只读
    @property
    def age(self):
        return self.__age


f = Fruit('Apple', '2 years ago')
print(f.name)  # Apple
f.name = 'Pie'
print(f.name)  # Pie
print(f.age)  # 2 years ago
# f.age = '4 years ago'  # AttributeError: can't set attribute


# 案例
class Screen(object):

    def __init__(self,width,height,resolution):
        self._width = width
        self._height = height
        self._resolution = resolution

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, width):
        self._width = width

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, height):
        self._height = height

    @property
    def resolution(self):
        return self._resolution


# 测试:
s = Screen(10,20,786432)
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
    print('测试通过!')
else:
    print('测试失败!')
